package com.xjrh.traintravel.collector.controller;

import com.alibaba.fastjson.JSONObject;
import com.xjrh.traintravel.collector.common.ResultData;
import com.xjrh.traintravel.collector.mq.KafkaProducer;
import com.xjrh.traintravel.collector.runner.NettyServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Date;

/**
 * 服务管理Controller
 *  <p>
 *      提供一些针对服务的操作方法，如：查看服务信息、服务下线等
 *  </p>
 * @author snps
 * @create 2022-01-17 13:56
 * @describe
 **/
@RequestMapping("/service/manage")
@RestController
@Slf4j
public class ServiceManageController {

    /**
     * NettyServer.port
     */
    @Value("${netty.server.port}")
    private int port;

    @Resource
    private NettyServer nettyServer;

    @Resource
    private KafkaProducer kafkaProducer;


    /****************************************************************
     * 进入服务初始页面
     * 		可用于查看服务是否正常运行、在集群部署环境中识别所访问的服务
     */
    @GetMapping({"", "/", "/index"})
    public String index() {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("ServiceInfo", "Hello! The service is: + " + "collector");
        jsonObj.put("Now is: " , new Date());
        return jsonObj.toString();
    }

    /**
     * 启动Netty服务
     * @return
     */
    // @PostMapping("/nettyServerStart")
    public ResultData nettyServerStart() {
        try {
            nettyServer.start(port);
        } catch (Exception e) {
            log.warn("NettyServer start...fail");
            e.printStackTrace();
        }

        ResultData data = new ResultData(Boolean.FALSE);
        data.setInfo("NettyServer start...fail");
        return data;
    }

    /**
     * 停止Netty服务
     * @return
     */
    // @PostMapping("/nettyServerStop")
    public ResultData nettyServerStop() {
        try {
            nettyServer.stop();
        } catch (Exception e) {
            log.warn("NettyServer stop...fail");
            e.printStackTrace();
        }

        ResultData data = new ResultData(Boolean.FALSE);
        data.setInfo("NettyServer stop...success");
        return data;
    }


}